<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>唤起程序</title>
  <script src="https://anquan.baidu.com/webstatic/lib/jquery.min.js"></script>
  <style>
    h4 {
      background-color: rgb(148, 240, 240);
    }

    .form-item {
      margin: 6px 0;
    }

    .form-item .form-item-label {
      display: inline-block;
      width: 170px;
    }

    .form-item input[type="checkbox"] {
      margin-right: 16px;
    }

    .form-item input[type="text"] {
      width: 400px;
    }

    #runExe1 {
      width: 200px;
      height: 50px;
      font-weight: bold;
      margin: 6px 0;
    }

    /*模态框主体样式*/
    .modal {
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      display: none;
    }

    /*模态框公共样式*/
    .modal-content {
      background-color: #17eca5;
      color: #fff;
      margin: 50px auto 0;
      padding: 20px;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
      animation: modal-show 0.3s;
    }

    /* 正常大小 */
    .modal-normal {
      width: 600px;
    }

    /* 中等大小 */
    .modal-medium {
      width: 400px;
    }

    /* 迷你大小 */
    .modal-mini {
      width: 250px;
    }

    /* 隐藏 */
    .modal-hide {
      animation: modal-hide 0.3s;
    }

    /* 展示动画 */
    @keyframes modal-show {
      from {
        opacity: 0;
        transform: translateY(-50px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    /* 隐藏动画 */
    @keyframes modal-hide {
      from {
        opacity: 1;
        transform: translateY(0);
      }

      to {
        opacity: 0;
        transform: translateY(-50px);
      }
    }
  </style>
</head>

<body id="app">
  <div id="modal" class="modal">
    <div class="modal-content modal-normal">
      <h2>数据已发送到客户端</h2>
    </div>
  </div>
  <h4>签章文件配置</h4>
  <div class="form-item">
    <span class="form-item-label">待签章文件路径: </span>
    <input id="awaitingSignatureFilePath" type="text" placeholder="如：C:/1.pdf">
    <input type="hidden" id="fileKey"/>
  </div>
  <div class="form-item">
    <span class="form-item-label">待签章文件名称：</span>
    <input id="awaitingSignatureFileName" type="text" disabled>
  </div>
  <div class="form-item">
    <span class="form-item-label">待签章文件类型：</span>
    <input id="awaitingSignatureFileType" type="text" placeholder="如：pdf">
  </div>
  <div class="form-item">
    <span class="form-item-label">签章文件保存路径：</span>
    <input id="signatureFileSavePath" type="text" placeholder="如：C:/保存文件夹">
  </div>
  <div class="form-item">
    <span class="form-item-label">签章文件保存名称：</span>
    <input id="signatureFileName" type="text" placeholder="如：签章完成文件">
  </div>
  <hr>
  <h4>系统环境配置</h4>
  <div class="form-item">
    <span class="form-item-label">tradingSystemCode：</span>
    <input id="tradingSystemCode" type="text">
  </div>
  <div class="form-item">
    <span class="form-item-label">serviceUrl：</span>
    <input id="serviceUrl" type="text">
  </div>
  <div class="form-item">
    <span class="form-item-label">clientId：</span>
    <input id="clientId" type="text">
  </div>
  <div class="form-item">
    <span class="form-item-label">clientSecret：</span>
    <input id="clientSecret" type="text">
  </div>
  <div class="form-item">
    <span class="form-item-label">signatureSecret：</span>
    <input id="signatureSecret" type="text">
  </div>
  <div class="form-item">
    <span class="form-item-label">callbackRequestUrl：</span>
    <input id="callbackRequestUrl" type="text">
  </div>
  <button id="runExe1">唤起程序</button>
  <button id="getCallBack" onclick="getCallBack()">获取回调</button>
  <a href="https://d45a52.link.yunpan.com/lk/surl_y9ktHkJQ6Kr#/">ca互认工具下载</a>
</body>
<script>
  function guid() {
    var s= 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0,
              v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
    s=s.replace(/-/g,'')
    return s
  }

  let socket = null
  let signatureSealComponentConfig = {
    document: [
      {
        // 待签章文件路径
        awaitingSignatureFilePath: 'C:/test.pdf',
        // 待签章文件名称
        awaitingSignatureFileName: 'test.pdf',
        // 待签章文件类型
        awaitingSignatureFileType: 'pdf',
        //签章后文件的保存路径
        signatureFileSavePath: 'D:/',
        // 签章后文件的名称
        signatureFileName: 'signed_test.pdf',
      }
    ],
    caShareComponentConfig: {
      // 交易系统编码
      // tradingSystemCode: 'DCS20210607',
      tradingSystemCode: '',
      //CA互认共享组件服务地址
      // serviceUrl: 'http://39.105.128.110:83',
      serviceUrl: '',
      // ClientID（用户名）
      clientId: '',
      // ClientSercet（密码）
      clientSecret: '',
      // 签名密钥
      signatureSecret: '',
    },
    tradingSystemConfig: {
      // 回调地址
      callbackRequestUrl: ''
    }
  }
  let mappingObj = {
    awaitingSignatureFilePath: 'document',
    awaitingSignatureFileName: 'document',
    awaitingSignatureFileType: 'document',
    signatureFileSavePath: 'document',
    signatureFileName: 'document',

    tradingSystemCode: 'caShareComponentConfig',
    serviceUrl: 'caShareComponentConfig',
    clientId: 'caShareComponentConfig',
    clientSecret: 'caShareComponentConfig',
    signatureSecret: 'caShareComponentConfig',

    callbackRequestUrl: 'tradingSystemConfig'
  }

  let awaitingSignatureFilePathIpt = $("#awaitingSignatureFilePath")
  let awaitingSignatureFileNameIpt = $("#awaitingSignatureFileName")
  let awaitingSignatureFileTypeIpt = $("#awaitingSignatureFileType")
  let signatureFileSavePathIpt = $("#signatureFileSavePath")
  let signatureFileNameIpt = $("#signatureFileName")

  let tradingSystemCodeIpt = $("#tradingSystemCode")
  let serviceUrlIpt = $("#serviceUrl")
  let clientIdIpt = $("#clientId")
  let clientSecretIpt = $("#clientSecret")
  let signatureSecretIpt = $("#signatureSecret")
  let callbackRequestUrlIpt = $("#callbackRequestUrl")

  initFn()

  //获取配置信息
  function getConfig(){
    return  $.ajax({
      url: '/nation/getconfig',
      type: 'GET',
      dataType: 'json'
    })
  }

  //获取签章回调数据
  function getCallBack(){
    $.ajax({
      url: '/nation/pdfback',
      type: 'post',
      dataType: 'json',
      data:{
        platFormCode: '12620000224333349J',
        systemCode: 'Body001',
        fileKey: $('#fileKey').val()
      },
      success: function (res) {
        console.log(res)
        if(res.code === 0){
          alert('签章回调信息:'+res.data[0].callData)
        }
      }
    })
  }
  function initFn() {
    awaitingSignatureFilePathIpt.val(signatureSealComponentConfig.document[0].awaitingSignatureFilePath)
    awaitingSignatureFileNameIpt.val(signatureSealComponentConfig.document[0].awaitingSignatureFileName)
    awaitingSignatureFileTypeIpt.val(signatureSealComponentConfig.document[0].awaitingSignatureFileType)
    signatureFileSavePathIpt.val(signatureSealComponentConfig.document[0].signatureFileSavePath)
    signatureFileNameIpt.val(signatureSealComponentConfig.document[0].signatureFileName)

    getConfig().then(
            function (res) {
              if(res.code === 0){
                //签章回调地址需要评价交易中心编码、系统编码、文件key，文件key需要每次都生成一个唯一标识
                var fileKey = guid()
                $('#fileKey').val(fileKey)
                var callBackUrl = res.data.signCallBackUrl+'?platFormCode=12620000224333349J&systemCode=Body001&fileKey='+fileKey
                tradingSystemCodeIpt.val(res.data.platformCode)
                serviceUrlIpt.val(res.data.apiUrl)
                clientIdIpt.val(res.data.clientId)
                clientSecretIpt.val(res.data.clientSecret)
                signatureSecretIpt.val(res.data.signatureSecret)
                callbackRequestUrlIpt.val(callBackUrl)

                signatureSealComponentConfig.caShareComponentConfig.tradingSystemCode=res.data.platformCode
                signatureSealComponentConfig.caShareComponentConfig.serviceUrl=res.data.apiUrl
                signatureSealComponentConfig.caShareComponentConfig.clientId=res.data.clientId
                signatureSealComponentConfig.caShareComponentConfig.clientSecret=res.data.clientSecret
                signatureSealComponentConfig.caShareComponentConfig.signatureSecret=res.data.signatureSecret
                signatureSealComponentConfig.tradingSystemConfig.callbackRequestUrl=callBackUrl
                console.log(signatureSealComponentConfig)
              }
              // 成功时的回调
              console.log('Config received:', res);
            },
            function (err) {
              // 失败时的回调
              console.error('Request failed:', err);
            }
      );
    $('.form-item input[type="text"]').on("input", function (evt) {
      let target = $(evt.target)
      let id = target.attr('id')
      let mKey = mappingObj[id]
      if (id === 'awaitingSignatureFilePath') {
        getAwaitingSignatureFileName()
      }
      if (Object.prototype.toString.call(signatureSealComponentConfig[mKey]) === '[object Array]') {
        signatureSealComponentConfig[mKey][0][id] = target.val()
      } else if (Object.prototype.toString.call(signatureSealComponentConfig[mKey]) === '[object Object]') {
        signatureSealComponentConfig[mKey][id] = target.val()
      }
    })

    $('#runExe1').on("click", function () {
      runExe1()
    })
  }

  getAwaitingSignatureFileName()
  function getAwaitingSignatureFileName() {
    let path = awaitingSignatureFilePathIpt.val()
    let regEx = /[^\\/]*(\.pdf)$/
    let pattern = path.match(regEx)
    if (pattern) {
      awaitingSignatureFileNameIpt.val(pattern[0])
      signatureSealComponentConfig.document[0].awaitingSignatureFileName = pattern[0]
    } else {
      awaitingSignatureFileNameIpt.val('待签章文件.pdf')
      signatureSealComponentConfig.document[0].awaitingSignatureFileName = '待签章文件.pdf'
    }
  }

  // 向编辑器发送执行请求
  function runExe1() {
    let flag = true
    for (let key in signatureSealComponentConfig.document[0]) {
      if (!signatureSealComponentConfig.document[0][key]) {
        flag = false
      }
    }
    if (!flag) {
      return alert("签章文件配置存在空值！")
    }
    if (socket.readyState !== 1) {
      let a = document.createElement('a')
      a.href = 'CAShareDetectInstallTool://websocket?flag=0'
      a.click()
    } else {
      const message = {
        CAShareUseScene: '00',
        keyParameter: signatureSealComponentConfig
      }
      socket.send(JSON.stringify(message))
      console.log(JSON.stringify(message))
      $('#modal').show()
      setTimeout(function () {
        $('#modal').hide()
      }, 2000)
    }
  }

  initSocket()
  function initSocket() {
    // 创建WebSocket连接
    socket = new WebSocket('ws://localhost:12345') //客户端程序，socket固定地址

    // 连接打开时的处理函数
    socket.onopen = function (event) {
      console.log('WebSocket is open now.')
      // $('#modal').show()
      // setTimeout(function () {
      //   const message = {
      //     CAShareUseScene: '00',
      //     keyParameter: signatureSealComponentConfig,
      //   }
      //   socket.send('Hello, server!')
      //   socket.send(JSON.stringify(message))
      //   $('#modal').hide()
      // }, 2000)
    }

    // 接收到消息时的处理函数
    socket.onmessage = function (event) {
      console.log('Received data from server: ', event.data)
      isDialog = true
      setTimeout(function () {
        isDialog = false
      }, 2000)
    }

    // 连接关闭时的处理函数
    socket.onclose = function (event) {
      setTimeout(function () {
        initSocket()
      }, 1000)
      console.log('WebSocket is closed now.')
    }

    // 连接出错时的处理函数
    socket.onerror = function (error) {
      console.error('WebSocket Error: ', error)
    }
  }
</script>

</html>